<template>
  <div class="statistics-report">
    <SearchForm
      v-model="searchParams"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 联合培养专业领域统计 -->
    <el-card class="report-card">
      <div class="report-header">
        <h2 class="report-title">
          联合培养领域共计<span class="highlight-number">{{
            trainFieldTotalCount
          }}</span
          >个
        </h2>
        <p class="report-subtitle">累计联合培养人数</p>
      </div>

      <!-- 柱状图容器 -->
      <div class="chart-container">
        <div ref="trainFieldChartRef" class="chart" v-loading="loading"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  nextTick,
  getCurrentInstance,
  watch,
} from "vue";
import SearchForm from "./searchForm.vue";
import {
  getTrainFieldCount,
  getTrainFieldStudentCount,
} from "@/api/statistics";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import { isPhone } from "@/utils/index";

const { proxy } = getCurrentInstance();

// 获取字典数据
const { specialty } = proxy.useDict('specialty')

// 搜索参数
const searchParams = ref({});

// 统计数据
const trainFieldTotalCount = ref(0);
const trainFieldStudent = ref([]);
const loading = ref(false);
const trainFieldChartRef = ref(null);
let trainFieldChartInstance = null;

// 获取专业领域显示名称（从字典中获取）
const getFieldFieldDisplayName = (fieldKey) => {
  const dictItem = specialty.value.find(item => item.value === fieldKey)
  return dictItem ? dictItem.label : fieldKey
}

// 初始化专业领域图表
const initTrainFieldChart = () => {
  if (!trainFieldChartRef.value) return;

  trainFieldChartInstance = echarts.init(trainFieldChartRef.value);

  // 处理数据，按人数降序排列
  const sortedData = [...trainFieldStudent.value].sort(
    (a, b) => b.studentCount - a.studentCount
  )

  // 使用中文名称作为类目
  const categories = sortedData.map((item) =>
    getFieldFieldDisplayName(item.trainField)
  )
  const values = sortedData.map((item) => item.studentCount)

  const option = {
    title: {
      show: false,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: function (params) {
        const data = params[0];
        return `${data.name}<br/>联合培养人数: ${data.value}`;
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      top: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: categories,
      axisLabel: {
        interval: 0,
        rotate: isPhone ? 45 : 30,
        fontSize: isPhone ? 8 : 10,
        color: "#606266",
        // align: "right",
      },
      axisLine: {
        lineStyle: {
          color: "#e0e0e0",
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        fontSize: 12,
        color: "#606266",
      },
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          color: "#f5f7fa",
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "联合培养人数",
        type: "bar",
        data: values,
        itemStyle: {
          color: "#409eff",
          borderRadius: [2, 2, 0, 0],
        },
        emphasis: {
          itemStyle: {
            color: "#66b1ff",
          },
        },
        label: {
          show: true,
          position: "top",
          fontSize: 12,
          color: "#303133",
          fontWeight: "bold",
        },
        barWidth: "60%",
      },
    ],
  };

  trainFieldChartInstance.setOption(option);
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    loading.value = true;

    // 获取专业领域总数
    const trainFieldCountRes = await getTrainFieldCount(searchParams.value);
    if (trainFieldCountRes.code === 200) {
      trainFieldTotalCount.value = trainFieldCountRes.data || 0;
    }

    // 获取专业领域学生统计
    const trainFieldStudentRes = await getTrainFieldStudentCount(
      searchParams.value
    );
    if (trainFieldStudentRes.code === 200) {
      trainFieldStudent.value = trainFieldStudentRes.data || [];
    }

    // 等待DOM更新后初始化图表
    await nextTick();

    // 初始化专业领域图表
    initTrainFieldChart();
  } catch (error) {
    console.error("加载统计数据失败:", error);
    ElMessage.error("加载统计数据失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  console.log("搜索参数:", searchParams.value);
  loadStatistics();
};

// 重置处理
const handleReset = () => {
  console.log("重置搜索");
  loadStatistics();
};

watch(
  trainFieldStudent,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      nextTick(() => {
        initTrainFieldChart();
      });
    }
  },
  { deep: true }
);

// 响应式调整
const handleResize = () => {
  if (trainFieldChartInstance) {
    trainFieldChartInstance.resize();
  }
};

// 组件挂载时加载数据
onMounted(() => {
  // loadStatistics();
  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理图表实例
onUnmounted(() => {
  if (trainFieldChartInstance) {
    trainFieldChartInstance.dispose();
    trainFieldChartInstance = null;
  }
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
.statistics-report {
  padding: 20px;
}

.report-card {
  margin-top: 20px;
}

.report-card:first-child {
  margin-top: 0;
}

.report-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.report-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.report-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
  text-align: right;
}

.highlight-number {
  color: #409eff;
  font-weight: bold;
  font-size: 1.2em;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .chart-container {
    height: 400px;
  }
}

@media (max-width: 768px) {
  .statistics-report {
    padding: 10px;
  }

  .report-title {
    font-size: 20px;
  }

  .report-subtitle {
    font-size: 14px;
  }

  .chart-container {
    height: 350px;
  }
}

@media (max-width: 480px) {
  .chart-container {
    height: 300px;
  }

  .report-title {
    font-size: 18px;
  }
}
</style>
